import { Inject, Injectable, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import pg from 'pg';

@Injectable()
export class DatabaseService implements OnModuleDestroy {
  public readonly pool: pg.Pool;

  constructor(@Inject(ConfigService) private readonly config: ConfigService) {
    const databaseUrl = this.config.get<string>('DATABASE_URL')
      || 'postgresql://app:app@localhost:5432/workease';

    this.pool = new pg.Pool({
      connectionString: databaseUrl,
      max: 5,
      // Avoid long startup blocks when DB is unreachable
      connectionTimeoutMillis: 5000,
    });
  }

  async ping(): Promise<void> {
    const client = await this.pool.connect();
    try {
      await client.query('select 1;');
    } finally {
      client.release();
    }
  }

  async useClient<T>(fn: (client: pg.PoolClient) => Promise<T>): Promise<T> {
    const client = await this.pool.connect();
    try {
      return await fn(client);
    } finally {
      client.release();
    }
  }

  async onModuleDestroy(): Promise<void> {
    await this.pool.end();
  }
}
